import * as types from '../action-types';
import {getSliders, getLessons} from '../../api/home'

interface setCategoryAction {
    type: string,
    playload: any
}

export type Action = setCategoryAction;

export default {
    setCategory(category):setCategoryAction {
        return {type: types.SET_CATEGORY, playload: category}
    },
    getSliders() {
        return function (dispatch, getState) {
            getSliders().then(res => {
                let {code, data} = res;
                if (code == 0) {
                    dispatch({type: types.SET_SLIDERS, playload: data})
                }
            })
        }
    },
    getLessons() {
        return function (dispatch, getState) {
            let {category, lessons: {offset, limit, hasMore, loading}} = getState().Home;
            if (!loading && hasMore) {
                dispatch({type: types.SET_HOME_LESSONS_LOADING})  
                getLessons(category, offset, limit).then(res => {
                    let {code, data} = res;
                    if (code == 0) {
                        dispatch({type: types.SET_LESSONS, playload: data})
                    }
                })    
            }
        }
    },
    reGetLessons() {
        return function (dispatch, getState) {
            let {category, lessons: {limit, loading}} = getState().Home;
            if (!loading) {
                dispatch({type:types.SET_HOME_LESSONS_LOADING});
                getLessons(category, 0, limit).then(res => {
                    let {code, data} = res;
                    if (code == 0) {
                        dispatch({type: types.RESET_LESSONS, playload: data})
                    }
                })    
            }
        }
    }
}